package top.zhangjianyong.utils.object;

import top.zhangjianyong.utils.coding.StringUtil;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: topzhangjianyongutils
 * @description: 基础OBJ
 * @author: 张建勇
 * @create: 2019-03-15 09:21
 **/
public class BaseObject {

    /**
     * 根据属性名获取属性值
     *
     * @param name
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public Object getAttributesByName(String name) throws NoSuchFieldException, IllegalAccessException {
        Field field = this.getClass().getDeclaredField(name);
        field.setAccessible(true);
        return field.get(this);
    }

    /**
     * 根据方法名执行方法
     *
     * @param methodName
     * @param parameter
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public Object invokeByMethodName(String methodName, String parameter) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = null;
        if (!StringUtil.isBlank(parameter)) {
            method = this.getClass().getDeclaredMethod(methodName);
            return method.invoke(this);
        } else {
            method = this.getClass().getDeclaredMethod(methodName, String.class);
            return method.invoke(this, parameter);
        }
    }


    public List<String> AllFieldNam() {
        Field[] fields = this.getClass().getDeclaredFields();
        List<String> list = new ArrayList<String>();
        for (Field field : fields) {
            list.add(field.getName());
        }
        return list;
    }

}
